import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_utils/flutter_baidu_mapapi_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/http/NoLoadingGetApi.dart';

import 'package:url_launcher/url_launcher.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../Tabbar/TabbarView.dart';
import '../../http/api.dart';
import '../EvaluationPage.dart';
import 'WaybillDetailsView.dart';
import 'package:platform/platform.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
class FreightPaymentSuccessful extends StatefulWidget {
  const FreightPaymentSuccessful({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<FreightPaymentSuccessful> createState() => _FreightPaymentSuccessfulState();
}

class _FreightPaymentSuccessfulState extends State<FreightPaymentSuccessful> {
  Map goodsData={};


  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        showCallPhoneFirstDialog(context);
        // 权限被拒绝，但用户可以再次授权
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }
  void getGoodsInfo(){
    NoLoadinggetApiManager.getData(
      context,
      "api/waybill/driver/waybill/getByGoodsId",
      {'goodsId':widget.dataMap['goodsId']},
          (responseData)  {
        setState(() {
          goodsData=responseData['data'];

        });

      },
    );
  }
  //添加熟车
  void addMyDrivertAction(String drvId)async{

  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getGoodsInfo();
  }
  void onOpenBaiduMapRoute(BMFOpenRouteType routeType) async {
    String? lat= await LatitudeManager.getLatitude();
    String? lon= await LongitudeManager.getLongitude();
    // BMFCoordinate startCoord = BMFCoordinate(double.parse(dataMap['loadPlaceInfo'][0]['latitude']), double.parse(dataMap['loadPlaceInfo'][0]['longitude']));

    BMFCoordinate  startCoord = BMFCoordinate(double.parse(lat!) , double.parse(lon!));

    // String startName = dataMap['loadPlaceInfo'][0]['detailedAddress'];
    String startName ="我的位置";
    String endName =goodsData['goodsInfo']['loadPlaceInfo'][0]['address'];
    BMFCoordinate endCoord = BMFCoordinate(goodsData['goodsInfo']['loadPlaceInfo'][0]['latitude'], goodsData['goodsInfo']['unloadPlaceInfo'][0]['longitude']);
    BMFOpenRouteOption routeOption = BMFOpenRouteOption(
        startCoord: startCoord,
        startName: startName,
        endCoord: endCoord,
        endName: endName,
        routeType: routeType,
        appScheme: 'baidumapsdk://mapsdk.baidu.com', // 指定返回自定义scheme
        isSupportWeb: true);
    BMFOpenErrorCode? flag =
    await BMFOpenMapUtils.openBaiduMapRoute(routeOption);
    print('open - route - errorCode = $flag');
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
    backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title: Text("费用支付成功",style: TextStyle(fontWeight: FontWeight.w300),),
        centerTitle: true,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
            );
          },
        ),
      ),
      body: ListView(children: [
        Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          padding: EdgeInsets.only(left: 20.w,top: 17.h,bottom: 16.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Row(
            children: [
              Icon(Icons.check_circle,color: Color.fromRGBO(116, 203, 135, 1),size: 50,),
              SizedBox(width: 7.w,),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("支付成功",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  Text("费用已支付至平台，请注意保留交易证据",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                ],
              ),
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          padding: EdgeInsets.only(right: 10.w,bottom: 8.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              BrnTagCustom(
                textPadding:EdgeInsets.only(left:12.w,right: 12.w),
                fontSize: 12.sp,
                tagText: '发货人',
                backgroundColor:MyColors.themeColor,
                tagBorderRadius: BorderRadius.only(topLeft: Radius.circular(10),bottomRight: Radius.circular(10)),
              ),
              SizedBox(height: 4.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      SizedBox(width: 22.w,),
                      if(goodsData.isNotEmpty)
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10.0), // 设置圆角半径
                        child: Image.network(
                          MyServiceUrl.imgHeader + goodsData['shipperInfo']['avatarPath'].toString(),
                          width: 36.w,
                          height: 36.h,
                          fit: BoxFit.cover, // 图片填充方式，可以根据需要调整
                        ),
                      ),

                      SizedBox(width:13.w ,),
                      if(goodsData.isNotEmpty)
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(goodsData['shipperInfo']['realName'].toString(),style: TextStyle(color: Colors.black),),
                          SizedBox(height: 3.h,),
                          Text(goodsData['shipperInfo']['phoneNum'].toString(),style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                        ],
                      ),
                    ],
                    
                  ),
                  Row(
                    children: [
                      GestureDetector(
                        child: Image.asset("lib/Images/OrderList/IMicon.png",width:24.w ,height: 24.h,),
                        onTap: (){},
                      ),
                      SizedBox(width: 8.w,),
                      GestureDetector(
                        child: Image.asset("lib/Images/OrderList/电话联系icon.png",width:24.w ,height: 24.h,),
                        onTap: (){

                          _makePhoneCall(widget.dataMap['shipperInfo']['phoneNum']);
                        },
                      ),
                    ],
                  )
                ],
              )
            ],
          ),
            ),
        Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          padding: EdgeInsets.only(top: 10.w,bottom: 10.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
                  SizedBox(),
              GestureDetector(
                child:  Column(
                  children: [
                    Image.asset("lib/Images/OrderList/支付成功查看运单.png",width: 40.w,height: 40.h,),

                    Text("查看运单",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                ),
                onTap: () async {
                  Navigator.push( context, FadeRoute(page:WaybillDetails(billId:goodsData['id'], type: 2,)));

                },
              ),

              GestureDetector(
                child: Column(
                  children: [
                    Image.asset("lib/Images/OrderList/支付去装货地icon.png",width: 40.w,height: 40.h,),
                    Text("去装货地",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                ),
                onTap: (){
                  onOpenBaiduMapRoute(BMFOpenRouteType.TruckRoute);
                },
              ),
              GestureDetector(
                child:  Column(
                  children: [
                    Image.asset("lib/Images/OrderList/支付分享证件icon.png",width: 40.w,height: 40.h,),

                    Text("分享证件",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                ),
                onTap: (){
                  addMyDrivertAction("2");
                },
              ),

              SizedBox(),
            ],
          ),
            ),
      ],
      ),
    );
  }
}
